<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\OrderChildsModel;
use App\Model\OrdersModel;
use App\Model\UsersLineUpModel;
use App\Services\Logger;
use App\Services\PayServices;
use Illuminate\Support\Facades\DB;

class OrdersDao extends BaseDao
{
    public static function get_order_builder($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = OrdersModel::query();

        $query->when(checkIsHasField($params,'order_id'),function ($query)use ($params){
            $query->where('order_id',$params['order_id']);
        });


        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $query->when(checkIsHasField($params,'order_code'),function ($query)use ($params){
            $query->where('order_code',$params['order_code']);
        });


        $query->when(checkIsHasField($params,'status'),function ($query)use ($params){
            $query->where('status',$params['status']);
        });


        return $query->with('goods');
    }


    public static function get_order_child_builder($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = OrderChildsModel::query();

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });


        $query->when(checkIsHasField($params,'order_code'),function ($query)use ($params){
            $query->where('order_code',$params['order_code']);
        });


        $query->when(checkIsHasField($params,'status'),function ($query)use ($params){
            $query->where('status',$params['status']);
        });

        $query->when(checkIsHasField($params,'h_user_id'),function ($query)use ($params){
            $query->where('h_user_id',$params['h_user_id']);
        });

        $query->when(checkIsHasField($params,'order_child_id'),function ($query)use ($params){
            $query->where('order_child_id',$params['order_child_id']);
        });

        return $query;
    }

    /**
     * @throws SysExceptions
     */
    public static function addOrder(array $params)
    {
        //检测项目id
        if(!checkIsHasField($params,'project_id')){
            self::error('请选择商品');
        }else if(!checkIsHasField($params,'nums')){
            self::error('请填写购买数量');
        }

        if(!checkIsHasField($params,'sku_attritubes')){
            $params['sku_attritubes:'] = 0;
        }

        if(!checkIsHasField($params,'sku_attributes_txt')){
            $params['sku_attributes_txt'] = '';
        }



        $userInfo = UsersDao::get_user_builder([
            'user_id'=>$params['user_id']
        ])->first()->toArray();
        $projectQuery = ProjectDao::get_projects_builder([
            'project_id'=>$params['project_id']
        ]);
        if(!$projectQuery->exists()){
            self::error('商品不存在');
        }
        $projectInfo = $projectQuery->first()->toArray();

        $price = $projectInfo['project_price'];
        $zhuan_query = UsersDao::get_shop_builder([
            'user_id'=>$params['user_id']
        ]);


        $order_data = [
            'user_id'=>$params['user_id'],
            'order_code'=>makeOrderNo(),
            'status'=>0
        ];
        $order_child_data = [
            'user_id'=>$params['user_id'],
            'order_code'=>$order_data['order_code'],
            'sku_attritubes'=>$params['sku_attritubes'],
            'sku_attributes_txt'=>$params['sku_attributes_txt'],
            'json_data'=>json_encode($projectInfo,JSON_UNESCAPED_UNICODE),
            'project_id'=>$params['project_id'],
            'nums'=>$params['nums'],
            'price'=>bcmul($params['nums'],$price,2),
        ];

        $order_data['price'] = $order_child_data['price'];

        DB::beginTransaction();
        $result = self::get_order_builder()->create($order_data);
        $result !== false && $result = self::get_order_child_builder()->create($order_child_data);
        if($result === false){
            DB::rollBack();
            self::error('下单失败');
        }
        DB::commit();
        //下单支付
        return PayServices::pay([
            'openid'=>$userInfo['openid'],
            'notify_url'=>route('notice_goods'),
            'price'=>$order_data['price'],
            'order_code'=>$order_data['order_code']
        ]);

    }

    /**
     * @throws SysExceptions
     */
    public static function addCarOrder(array $params)
    {
        if(!checkIsHasField($params,'car_id')){
            self::error('请选择购物车id');
        }
        $car_data = explode(',',$params['car_id']);
        if(count($car_data) < 1){
            self::error('数据异常');
        }
        $car_mysql_query = CarsDao::get_cars_builder([
            'user_id'=>$params['user_id']
        ])->whereIn('car_id',$car_data);
        if(!$car_mysql_query->exists()){
            self::error('购物车不存在');
        }
        $car_mysql_data = $car_mysql_query->get()->toArray();
        $inserDataChild = [];
        $priceAll = 0;
        $order_code = makeOrderNo();

        foreach ($car_mysql_data as $value){

            $projectQuery = ProjectDao::get_projects_builder([
                'project_id'=>$value['project_id']
            ]);

            if(!$projectQuery->exists()){
                self::error('商品不存在');
            }
            $projectInfo = $projectQuery->first()->toArray();

            $price = $projectInfo['project_price'];
            $zhuan_query = UsersDao::get_shop_builder([
                'user_id'=>$params['user_id']
            ]);
            //如果是专卖店按照专卖店价格
            $userInfo = UsersDao::get_user_builder([
                'user_id'=>$params['user_id']
            ])->first()->toArray();
            $type = 0;
            //Vip价格
            if($userInfo['vip_level'] != 0){
                $str = ['','vip_price','vip_price_2','vip_price_3'];
                $price = $projectInfo[$str[$userInfo['vip_level']]];

            }
            if($zhuan_query->exists()){
                $price = $projectInfo['zhuanmai_price'];
                $type = 1;
            }else{
                if($projectInfo['is_zhuanmai'] == 1){
                    self::error('特供专卖店!');
                }
            }

            $inserDataChild[] = [
                'user_id'=>$params['user_id'],
                'order_code'=>$order_code,
                'json_data'=>json_encode($projectInfo,JSON_UNESCAPED_UNICODE),
                'project_id'=>$value['project_id'],
                'nums'=>$value['num'],
                'price'=>bcmul($value['num'],$price,2),
                'created_at'=>time(),
                'type'=>$type
            ];
            $priceAll = bcadd(bcmul($value['num'],$price,2),$priceAll,2);
        }
        $inserOrderData = [
            'order_code'=>$order_code,
            'price'=>$priceAll,
            'user_id'=>$params['user_id'],
            'status'=>0
        ];
        DB::beginTransaction();
        $result = self::get_order_builder()->create($inserOrderData);
        $result !== false && $result = self::get_order_child_builder()->insert($inserDataChild);
        //删除购物车
        $result !== false && $result = $car_mysql_query->delete();
        if($result === false){
            DB::rollBack();
            self::error('下单失败');
        }
        DB::commit();
    }

    public static function get_orders(array $params)
    {
        $list =  self::get_order_child_builder($params)->with('userInfo')->orderByDesc('created_at')->get();
        foreach ($list as &$value){
            $value['json_data'] = json_decode($value['json_data'],true);
        }
        return $list;
    }

    public static function get_user_order_info(array $params)
    {
        return self::get_order_child_builder($params)->with('orderInfo')->with('userInfo')->first();
    }

    /**
     * @throws SysExceptions
     */
    public static function hexiao(array $params)
    {
        if(!checkIsHasField($params,'hnums')){
            self::error('请填写核销数量');
        }
        $order_child_query = self::get_order_child_builder([
            'order_child_id'=>$params['order_child_id'],
            'status'=>0,
        ]);
        if(!$order_child_query->exists()){
            self::error('订单状态不正确');
        }
        $order_child_info = $order_child_query->first()->toArray();
        $user_stock_query = UserStockDao::get_user_stock_builder([
            'user_id'=>$params['he_user_id'],
            'project_id'=>$order_child_info['project_id']
        ]);
        if(!$user_stock_query->exists()){
            self::error('商品库存不存在');
        }
        $user_stock_info = $user_stock_query->first()->toArray();
        if($user_stock_info['nums'] < $params['hnums']){
            self::error('库存不足');
        }

        if($order_child_info['status'] !=0){
            self::error('订单状态不正确!');
        }

        if($order_child_info['nums'] < $params['hnums']){
            self::error('核销数量不正确');
        }

        if($order_child_info['type'] != 0){
            self::error('订单类型不正确');
        }
        //修改订单状态
        DB::beginTransaction();
        $result = $order_child_query->update([
            'hnums'=>$params['hnums'],
            'status'=>2,
            'hprice'=>bcmul(bcdiv($order_child_info['price'],$order_child_info['nums'],2),$params['hnums'],2),
            'h_user_id'=>$params['he_user_id'],
            'hexiao_time'=>time()
        ]);
        $result !== false && $result = $user_stock_query->decrement('nums',$params['hnums']);
        if($result === false){
            DB::rollBack();
            self::error('核销失败');
        }
        DB::commit();
    }

    public static function get_orders_page(array $all): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        return self::get_order_child_builder($all)->with('orderInfo')->with('projectInfo')->with('userInfo')->orderByDesc('created_at')->paginate();
    }

    /**
     * @param array $all
     * @return void
     * @throws SysExceptions
     */
    public static function send_huo(array $all)
    {
        if(self::get_order_child_builder([
            'order_child_id'=>$all['order_child_id']
        ])->update([
            'status'=>3,
            'wuliu_num'=>$all['wuliu_num']
        ]) === false){
            self::error('发货失败');
        }
    }

    public static function confirm_order(array $params)
    {
        $order_child_query = OrdersDao::get_order_child_builder([
            'user_id'=>$params['user_id'],
            'order_child_id'=>$params['order_child_id'],
            'status'=>3
        ]);
        if(!$order_child_query->exists()){
            self::error('订单不存在!');
        }
        $order_child_info = $order_child_query->first()->toArray();
        $json_data = json_decode($order_child_info['json_data'],true);
        DB::beginTransaction();
        $result = $order_child_query->update([
            'status'=>4
        ]);
        //查询库存有没有这个商品
        $user_stock_query = UserStockDao::get_user_stock_builder([
            'user_id'=>$order_child_info['user_id'],
            'project_id'=>$order_child_info['project_id']
        ]);
        if($user_stock_query->exists()){
            $result !== false && $result = $user_stock_query->increment('nums',$order_child_info['nums']);
        }else{
            $result !== false && $result = $user_stock_query->create([
                'user_id'=>$order_child_info['user_id'],
                'project_id'=>$order_child_info['project_id'],
                'nums'=>$order_child_info['nums'],
                'category_id'=>$json_data['category_id']
            ]);
        }

        if($result === false){
            DB::rollBack();
            self::error('失败');
        }
        DB::commit();
    }

    public static function get_order_child_he(array $all)
    {
        return self::get_order_child_builder($all)->where('h_user_id','<>',0)->with('he_shops_user.shopInfo')->paginate();
    }

    /**
     * @throws SysExceptions
     */
    public static function changeOrder($out_trade_no)
    {

        $orderQuery = self::get_order_builder([
            'order_code'=>$out_trade_no,
            'status'=>0
        ]);

        if(!$orderQuery->exists()){
            Logger::pay_success("=====>error",[
                $out_trade_no
            ]);
            self::error('订单不存在');
        }
        $orderInfo = $orderQuery->first()->toArray();
        if($orderQuery->update([
            'status'=>1
        ]) === false){
            self::error('失败了');
        }
        //获取下单人信息
        self::changeOrderAuto($out_trade_no);

    }

    /**
     * @param $out_trade_no
     * @return void
     * @throws SysExceptions
     */
    private static function changeOrderAuto($out_trade_no)
    {
        $orderQuery = self::get_order_builder([
            'order_code'=>$out_trade_no,
            'status'=>1
        ]);

        if(!$orderQuery->exists()){
            Logger::pay_success("=====>error",[
                $out_trade_no
            ]);
            self::error('已支付订单不存在');
        }
        $orderInfo = $orderQuery->first()->toArray();
        $userInfo = UsersDao::get_user_builder([
            'user_id'=>$orderInfo['user_id']
        ])->first()->toArray();

        DB::beginTransaction();
        try {

            $goodsInfo = json_decode($orderInfo['goods'][0]['json_data'],true);
            $now_price = 0;
            //自购返现
            if($goodsInfo['me_rate_price'] > 0){
                //获取用户消费金额
                $order_user_price = self::get_order_builder([
                    'user_id'=>$orderInfo['user_id']
                ])->where('status',2)->sum('price');
                //获取所有的返费
                $yijing_price = BillDao::get_bill_builder([
                    'user_id'=>$orderInfo['user_id'],
                    'pm'=>1,
                ])->where('title','下级购买商品')->where('title','自购返现')->sum('num');
                if($order_user_price > $yijing_price){
                    BillDao::get_bill_builder()->create([
                        'from_user_id'=>$orderInfo['user_id'],
                        'user_id'=>$userInfo['user_id'],
                        'pm'=>1,
                        'type'=>1,
                        'num'=>bcmul($goodsInfo['me_rate_price'],$orderInfo['price'],2),
                        'title'=>'自购返现',
                        'status'=>1,
                        'relation_id'=>$orderInfo['order_id']
                    ]);
                    UsersDao::get_user_builder([
                        'user_id'=>$userInfo['user_id'],
                    ])->increment('money',bcmul($goodsInfo['me_rate_price'],$orderInfo['price'],2));
                    $now_price = bcmul($goodsInfo['me_rate_price'],$orderInfo['price'],2);
                }
            }

            //有上级
            if($userInfo['spread_id'] != 0){
                $goodsInfo = json_decode($orderInfo['goods'][0]['json_data'],true);
                $order_user_price = self::get_order_builder([
                    'user_id'=>$userInfo['spread_id']
                ])->where('status',2)->sum('price');
                //获取所有的返费
                $yijing_price = BillDao::get_bill_builder([
                    'user_id'=>$userInfo['spread_id'],
                    'pm'=>1,
                ])->where('title','下级购买商品')->where('title','自购返现')->sum('num');
                if($order_user_price > $yijing_price) {

                    //上级返现
                    BillDao::get_bill_builder()->create([
                        'from_user_id' => $orderInfo['user_id'],
                        'user_id' => $userInfo['spread_id'],
                        'pm' => 1,
                        'type' => 1,
                        'num' => bcsub(bcmul($goodsInfo['spread_rate_price'], $orderInfo['price'], 2),$now_price,2),
                        'title' => '下级购买商品',
                        'status' => 1,
                        'relation_id' => $orderInfo['order_id']
                    ]);
                    UsersDao::get_user_builder([
                        'user_id' => $userInfo['spread_id'],
                    ])->increment('money', bcsub(bcmul($goodsInfo['spread_rate_price'], $orderInfo['price'], 2),$now_price,2));
                }
            }else{
                $goodsInfo = json_decode($orderInfo['goods'][0]['json_data'],true);
                //查询是否有待返费的人
                $userLineUp = UsersLineUpModel::query()->whereRaw('(money_now_price < money)');
                //如果存在
                if($userLineUp->exists()){
                    //判断是不是自己
                    $userLineUpInfo = $userLineUp->first()->toArray();
                    $up_price = $goodsInfo['spread_rate_price'];
                    if($userLineUpInfo['user_id'] == $orderInfo['user_id']){
                        $up_price = $goodsInfo['me_rate_price'];
                    }
                    $money_auo = $userLineUpInfo['money'] - $userLineUpInfo['money_now_price'];
                    if($money_auo < $up_price){
                        $up_price = $money_auo;
                    }
                    BillDao::get_bill_builder()->create([
                        'from_user_id'=>$orderInfo['user_id'],
                        'user_id'=>$userLineUpInfo['user_id'],
                        'pm'=>1,
                        'type'=>1,
                        'num'=>$up_price,
                        'title'=>'队列返现',
                        'status'=>1,
                        'relation_id'=>$orderInfo['order_id']
                    ]);
                    UsersDao::get_user_builder([
                        'user_id'=>$userLineUpInfo['user_id'],
                    ])->increment('money',$up_price);
                    UsersLineUpModel::query()->where('id',$userLineUpInfo['id'])->increment('money_now_price',$up_price);
                }
                //不存在什么都不用整
            }



            //判断是否满足进入的条件
            $sys = SettingsDao::buildParms();
            $time = time();
            //判断时间，处于开始状态
            if(($sys['users_buy_end_time'] >= $time && $sys['users_buy_start_time'] <= $time) && $sys['users_buy_end_time'] != 0 && $sys['users_buy_start_time'] != 0){
                //判断人数
                $userLineUpCount = UsersLineUpModel::query()->where('user_activity_id',$sys['user_activity_id'])->count();
                if($userLineUpCount < $sys['users_buy_max_count']){
                    //进入队列
                    if($sys['users_buy_price'] <= $orderInfo['price']){
                        UsersLineUpModel::query()->create([
                            'user_id'=>$orderInfo['user_id'],
                            'order_id'=>$orderInfo['order_id'],
                            'money'=>$orderInfo['price'],
                            'money_now_price'=>0,
                            'user_activity_id'=>$sys['user_activity_id']
                        ]);
                    }
                }
            }
            //给供应商返现



            $orderQuery->update([
                'status'=>2
            ]);
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            Logger::pay_success("====>error",[
                $exception->getMessage()
            ]);
            self::error('订单返钱失败'.$exception->getMessage());
        }
    }


}
